package com.android.lovepick;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.NavUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;

import com.android.lovepick.http.HttpThread;
import com.android.lovepick.util.BaseUtils;
import com.android.lovepick.util.Constant;

/**
 * @author MR
 */
public class LoginActivity extends Activity
{
	private static final String LOGIN_TAG = "LoginActivity";
	private EditText edtUserName;
	private EditText edtPassword;

	private String username;
	private String password;
	private ProgressDialog mDialog;
	private HttpThread mThread;
	private LoginHandler mHandler;

	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.login);
		BaseUtils.setUpActionBar(this);
		mDialog = new ProgressDialog(this);
		mHandler = new LoginHandler(this);
		findView();

		Map<String, String> map = MainApp.mainApp.getLogin();
		if (map != null)
		{
			Log.i(LOGIN_TAG, "自动登录");
			username = map.get("username");
			Log.i(LOGIN_TAG, "username: " + username);
			password = map.get("password");
			Log.i(LOGIN_TAG, "password: " + password);
			Intent intent = new Intent(LoginActivity.this,
					UserInfoActivity.class);
			intent.putExtra("username", username);
			startActivity(intent);
			// Intent service = new Intent(LoginActivity.this,
			// GetNewMsgService.class);
			// service.putExtra("LastID", 0);
			// startService(service);
			finish();
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu)
	{
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item)
	{
		switch (item.getItemId())
		{
			case android.R.id.home:
				NavUtils.navigateUpFromSameTask(this);
				return true;
		}
		return super.onOptionsItemSelected(item);
	}

	private void findView()
	{
		edtUserName = (EditText) this.findViewById(R.id.edt_nickname_login);
		edtPassword = (EditText) this.findViewById(R.id.edt_password_login);
	}

	/**
	 * 登录按钮事件
	 * 
	 * @param v
	 *            包含登录按钮的视图
	 */
	public void doLogin(View v)
	{
		if (MainApp.mainApp.getLogin() == null)
		{
			username = edtUserName.getText().toString();
			Log.i(LOGIN_TAG, "username:" + username);
			password = edtPassword.getText().toString();
			Log.i(LOGIN_TAG, "password:" + password);
		}

		if (BaseUtils.checkEmptyString(username)
				|| BaseUtils.checkEmptyString(password))
		{
			BaseUtils.showToast(this, "用户名或密码不能为空!");
		}
		else
		{
			List<NameValuePair> params = new ArrayList<NameValuePair>();
			params.add(new BasicNameValuePair("ID", username));
			params.add(new BasicNameValuePair("Password", password));
			params.add(new BasicNameValuePair("rememberMe", "true"));
			mThread = new HttpThread(mHandler, Constant.HTTP_METHOD_POST,
					Constant.HTTP_LOGIN_URL, params);
			mThread.start();
			mDialog.show();
		}

	}

	public void doReg(View v)
	{
		Intent intent = new Intent(v.getContext(), RegActivity.class);
		startActivity(intent);
		finish();
	}

	/**
	 * @return the username
	 */
	public String getUsername()
	{
		return username;
	}

	/**
	 * @return the password
	 */
	public String getPassword()
	{
		return password;
	}

	private static class LoginHandler extends Handler
	{
		private final String LOGIN_HANDLER_TAG = "LoginHandler";
		private WeakReference<LoginActivity> mReference;
		private LoginActivity mActivity;

		public LoginHandler(LoginActivity activity)
		{
			mReference = new WeakReference<LoginActivity>(activity);
		}

		@Override
		public void handleMessage(Message msg)
		{
			mActivity = mReference.get();
			switch (msg.what)
			{
				case Constant.MSG_HTTP_ERROR:
					mActivity.mDialog.dismiss();
					BaseUtils.showToast(mActivity, "连接服务器失败!");
					break;

				case Constant.MSG_HTTP_SUCCESS:
					Log.i(LOGIN_HANDLER_TAG, "get http result");
					String result = msg.getData().getString("http_result");
					Log.i(LOGIN_HANDLER_TAG, "http_result:" + result);
					if (result.equals("ok"))
					{
						Log.i(LOGIN_HANDLER_TAG, "login success...");
						BaseUtils.showToast(mActivity, "Login sucess!");

						Map<String, String> loginMap = new HashMap<String, String>();
						loginMap.put("username", mActivity.getUsername());
						loginMap.put("password", mActivity.getPassword());
						Log.i(LOGIN_HANDLER_TAG, "保存登录信息");
						MainApp.mainApp.setLogin(loginMap);
						Intent intent = new Intent(mActivity,
								UserInfoActivity.class);
						intent.putExtra("username", mActivity.getUsername());
						mActivity.startActivity(intent);
						mActivity.mDialog.dismiss();
						mActivity.finish();

					}
					else if (result.equals("login_error"))
					{
						Log.i(LOGIN_HANDLER_TAG, "login failed...");
						BaseUtils.showToast(mActivity, "用户名密码不匹配!");
						mActivity.mDialog.dismiss();
					}
					break;

				default:
					mActivity.mDialog.dismiss();
					break;
			}
		}
	}

}
